﻿define(function (require, exports, module) {
    var _toJSON = function (o) {
        if (typeof (JSON) == 'object' && JSON.stringify)
            return JSON.stringify(o);

        var type = typeof (o);

        if (o === null)
            return "null";

        if (type == "undefined")
            return undefined;

        if (type == "number" || type == "boolean")
            return o + "";

        if (type == "string")
            return $.quoteString(o);

        if (type == 'object') {
            if (typeof o.toJSON == "function")
                return _toJSON(o.toJSON());
            if (o.constructor === Date)
                return o.toEpoch();
            if (o.constructor === Array) {
                var ret = [];
                for (var i = 0; i < o.length; i++)
                    ret.push(_toJSON(o[i]) || "null");

                return "[" + ret.join(",") + "]";
            }

            var pairs = [];
            for (var k in o) {
                var name;
                var type = typeof k;

                if (type == "number")
                    name = '"' + k + '"';
                else if (type == "string")
                    name = $.quoteString(k);
                else
                    continue;  //skip non-string or number keys

                if (typeof o[k] == "function")
                    continue;  //skip pairs where the value is a function.

                var val = _toJSON(o[k]);

                pairs.push(name + ":" + val);
            }

            return "{" + pairs.join(", ") + "}";
        }
    };

    var _ToObject = function (obj) {
        return eval('(' + obj + ')');
    };

    var _AsyncMethod = function (url, methodType) {
        return function returnMethod(callback, args, beforeCallback, afterCallback) {
            if (beforeCallback) beforeCallback();

            if (methodType && methodType.toLowerCase() == 'post')
                $.post(
                    url,
                    args,
                     function (e) {
                         callback(e);
                         if (afterCallback) afterCallback();
                     });

            else
                $.getJSON(
                        url,
                        args,
                        function (e) {
                            callback(e);
                            if (afterCallback) afterCallback();
                        });
        };
                };

    var _SyncMethod = function (url, methodType) {
        return function returnMethod(callback, args, beforeCallback, afterCallback) {
            if (beforeCallback) beforeCallback();

            if (methodType && methodType.toLowerCase() == 'post') {
                $.ajax({
                    url: url,   //接收页面
                    type: 'post',      //POST方式发送数据
                    async: false,      //ajax同步
                    data: args,
                    dataType: 'json',
                    success: function (e) {
                        callback(e);
                        if (afterCallback) afterCallback();
                    }
                });
            } else {
                $.ajax({
                    url: url,
                    type: 'get',
                    async: false,
                    data: args,
                    dataType: 'json',
                    success: function (e) {
                        callback(e);
                        if (afterCallback) afterCallback();
                    }
                });
            }
        };
    };

    var _HandleATag = function (aTagItem, callback, feedId) {
        var $aTagItem = $(aTagItem);
        var url = $aTagItem.attr('href');
        $aTagItem.attr('href', '#').unbind();
        $aTagItem.click(function (event) {
            if (url.indexOf('target=action') == -1)
                $.postMessage('url:' + url, '*', parent);
            else {
                $.postMessage('action:' + url + '|' + feedId, '*', parent);
            }
            if (callback)
                callback();

            event.preventDefault();
            event.stopPropagation();
        });
    };

    var _GetCurrentDay = function (date) {
        if (!date) date = new Date();

        return new Date(
            Date.fromTicks(date).getFullYear(),
            Date.fromTicks(date).getMonth(),
            Date.fromTicks(date).getDate()
        ).toTicks();
    }

    var _AjaxLoad = {
        _displayDelayTimerId: null,
        _displayDelay: 1000,
        AjaxLoadBegin: function (beginCallback) {
            var _self = this;
            if (_self._displayDelayTimerId) {
                clearTimeout(_self._displayDelayTimerId);
            }

            _self._displayDelayTimerId = setTimeout(function () {
                $('.ui-remind').html('').addClass('busy').show();
                $('.ui-loading').css({
                    left: $('.content').width() / 2 - $('.ui-loading').width() / 2 - 14
                });
                $('.ui-loading').show();
                if (beginCallback) beginCallback();
            }, _self._displayDelay);
        },
        AjaxLoadEnd: function (endCallback) {
            var _self = this;

            if (_self._displayDelayTimerId) {
                clearTimeout(_self._displayDelayTimerId);
            }
            $('.ui-remind').hide().removeClass('busy');
            $('.ui-loading').hide();
            if (endCallback) endCallback();
        }
    }

    var _BottomMenu = {
        functionContainerTemplate:
            '<img class="img-menu" src="{image}" title="" alt="" />',

        dockOptions: {
            align: 'bottom'
            , size: 24
            , labels: 'tc'
            , distance: 40
        },

        createElement: function (functionData, dom) {
            var self = this;
            var elementHTML = self.functionContainerTemplate
                            .replace('{title}', functionData.title)
                            .replace('{image}', functionData.image);

            $(elementHTML)
                .appendTo($(dom))
                .click(function (event) {
                    event.preventDefault();
                    event.stopPropagation();

                    self.functionCall('http://' + document.location.host + functionData.url);
                });
        },

        functionCall: function (url) {
            if (url.indexOf('target=action') == -1)
                $.postMessage('url:' + url, '*', parent);
            else {
                //发给main.html
                $.postMessage('action:' + url, '*', parent);
            }
        },

        setJDock: function (dom, functionItems) {
            var self = this;
            for (var key in functionItems) {
                self.createElement(functionItems[key], dom);
            }
            $(dom).jqDock(this.dockOptions);
        }
    }
    

    return {
        toJSON: _toJSON,
        ToObject: _ToObject,
        AsyncMethod: _AsyncMethod,
        SyncMethod: _SyncMethod,
        HandleATag: _HandleATag,
        GetCurrentDay: _GetCurrentDay,
        AjaxLoad: _AjaxLoad,
        BottomMenu: _BottomMenu
    };

});